<template>
  <!-- 员工列表页面 -->
  <div class="employee-page">
    <Return />
    <div class="employee-header" :style="{ paddingTop: capsuleTop + 'px' }">
      <div class="employee-header-title">员工管理</div>
      <!-- <div class="employee-header-actions">
        <div class="add-btn" @click="showAddDialog">
          <wd-icon name="add" size="20px" color="#191919" />
          <span>添加员工</span>
        </div>
      </div> -->
    </div>

    <!-- 搜索栏 -->
    <!-- <div class="search-section">
      <wd-search
        v-model="searchKeyword"
        placeholder="搜索员工姓名、手机号"
        @search="handleSearch"
        @clear="handleClear"
      />
    </div> -->

    <!-- 员工列表 -->
    <scroll-view class="employee-content" scroll-y="true" :style="{ height: contentHeight + 'px' }"
      @scrolltolower="loadMore" refresher-enabled="true" :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh">
      <!-- 加载状态 -->
      <div v-if="loading && employeeList.length === 0" class="loading-container">
        <div class="loading-text">加载中...</div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!loading && employeeList.length === 0" class="empty-container">
        <wd-icon name="user" size="60px" color="#CCCCCC" />
        <div class="empty-text">暂无员工数据</div>
        <div class="empty-btn" @click="showAddDialog">添加员工</div>
      </div>

      <!-- 员工列表 -->
      <template v-else>
        <div v-for="(employee, index) in employeeList" :key="employee.id" class="employee-item"
          @click="viewEmployeeDetail(employee)">
          <div class="employee-avatar">
            <img :src="employee.avatar || '../static/imgs/touxiang.png'" alt="头像" @error="handleImageError" />
            <div class="status-badge" :class="{
              'status-active': employee.status === 1,
              'status-inactive': employee.status === 0
            }">
              {{ employee.status === 1 ? '在职' : '离职' }}
            </div>
          </div>

          <div class="employee-info">
            <div class="employee-name">
              <span class="name">{{ employee.customerName }}</span>
              <span class="job-title">{{ employee.type === 'ADMIN' ? '管理员' : '员工' }}</span>
            </div>
            <!-- <div class="employee-details">
              <div class="detail-item">
                <wd-icon name="phone" size="14px" color="#999" />
                <span>{{ employee.phone || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <wd-icon name="calendar" size="14px" color="#999" />
                <span>入职时间：{{ formatDate(employee.joinDate) }}</span>
              </div>
              <div class="detail-item" v-if="employee.department">
                <wd-icon name="location" size="14px" color="#999" />
                <span>{{ employee.department }}</span>
              </div>
            </div> -->
          </div>

          <div class="employee-actions">
            <!-- <div class="action-btn edit-btn" @click.stop="editEmployee(employee)">
              <wd-icon name="edit" size="16px" color="#F9DC40" />
            </div> -->
            <div class="action-btn delete-btn" @click.stop="confirmDelete(employee)">
              <wd-icon name="delete" size="16px" color="#FF6B6B" />
            </div>
          </div>
        </div>
      </template>

      <!-- 加载更多 -->
      <div v-if="loadingMore" class="loading-container">
        <div class="loading-text">加载更多...</div>
      </div>
    </scroll-view>

    <!-- 添加/编辑员工弹窗 -->
    <wd-popup v-model="showEmployeeDialog" position="center" :close-on-click-modal="false">
      <div class="employee-dialog">
        <div class="dialog-header">
          <div class="dialog-title">{{ isEditing ? '编辑员工' : '添加员工' }}</div>
          <div class="dialog-close" @click="closeDialog">
            <wd-icon name="close" size="20px" color="#999" />
          </div>
        </div>

        <div class="dialog-content">
          <wd-form ref="formRef" :model="formData" :rules="formRules">
            <!-- 头像上传 -->
            <div class="avatar-upload">
              <div class="upload-area" @click="uploadAvatar">
                <img v-if="formData.avatar" :src="formData.avatar" alt="头像" class="uploaded-avatar" />
                <div v-else class="upload-placeholder">
                  <wd-icon name="camera" size="30px" color="#CCCCCC" />
                  <div>点击上传头像</div>
                </div>
              </div>
            </div>

            <wd-form-item label="姓名" prop="name">
              <wd-input v-model="formData.name" placeholder="请输入员工姓名" />
            </wd-form-item>

            <wd-form-item label="手机号" prop="phone">
              <wd-input v-model="formData.phone" placeholder="请输入手机号" type="tel" />
            </wd-form-item>

            <wd-form-item label="职位" prop="jobTitle">
              <wd-input v-model="formData.jobTitle" placeholder="请输入职位" />
            </wd-form-item>

            <wd-form-item label="部门" prop="department">
              <wd-input v-model="formData.department" placeholder="请输入部门" />
            </wd-form-item>

            <wd-form-item label="入职时间" prop="joinDate">
              <wd-datetime-picker v-model="formData.joinDate" type="date" placeholder="请选择入职时间" />
            </wd-form-item>

            <wd-form-item label="状态" prop="status">
              <wd-radio-group v-model="formData.status">
                <wd-radio :value="1">在职</wd-radio>
                <wd-radio :value="0">离职</wd-radio>
              </wd-radio-group>
            </wd-form-item>

            <wd-form-item label="备注" prop="remark">
              <wd-input v-model="formData.remark" type="textarea" placeholder="请输入备注信息" :rows="3" />
            </wd-form-item>
          </wd-form>
        </div>

        <div class="dialog-footer">
          <wd-button @click="closeDialog" size="large" type="default">取消</wd-button>
          <wd-button @click="submitForm" size="large" type="primary" :loading="submitting">
            {{ isEditing ? '保存' : '添加' }}
          </wd-button>
        </div>
      </div>
    </wd-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from 'vue'
import { Fetch } from '@/composables/useFetch'
import { baseUrl } from '@/utils/config'
import Return from '@/components/Return.vue'
import { useLoginStore } from '@/stores/login'

const loginStore = useLoginStore()

// 响应式数据
const capsuleTop = ref(0)
const contentHeight = ref(0)
const loading = ref(false)
const loadingMore = ref(false)
const refreshing = ref(false)
const submitting = ref(false)
const employeeList = ref([])
const page = ref(1)
const hasMore = ref(true)
const searchKeyword = ref('')

// 弹窗状态
const showEmployeeDialog = ref(false)
const showDeleteConfirm = ref(false)
const isEditing = ref(false)
const currentDeleteEmployee = ref(null)

// 筛选状态
const activeFilterTab = ref('all')
const filterTabs = ref([
  { label: '全部', value: 'all' },
  { label: '在职', value: 'active' },
  { label: '离职', value: 'inactive' }
])

// 员工统计
const employeeStats = ref({
  total: 0,
  active: 0,
  inactive: 0
})

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  phone: '',
  jobTitle: '',
  department: '',
  joinDate: '',
  status: 1,
  avatar: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入员工姓名' }
  ],
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
  ],
  joinDate: [
    { required: true, message: '请选择入职时间' }
  ]
}

const formRef = ref()

// 页面初始化时获取shopId
const shopId = ref('')
onLoad((options) => {
  shopId.value = options.shopId || ''
})

// 计算内容区高度
function calcContentHeight() {
  const systemInfo = uni.getSystemInfoSync()
  // #ifdef MP-WEIXIN
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  capsuleTop.value = menuButtonInfo.bottom + 20
  // #endif
  // #ifndef MP-WEIXIN
  capsuleTop.value = systemInfo.statusBarHeight + 44
  // #endif
  contentHeight.value = systemInfo.windowHeight - capsuleTop.value - 200
}

// 获取员工列表
const getEmployeeList = async (isRefresh = false) => {
  if (loading.value && !isRefresh) return

  if (isRefresh) {
    page.value = 1
    hasMore.value = true
  }

  if (!hasMore.value) return

  loading.value = true
  loadingMore.value = !isRefresh

  try {
    const params = {
      shopId: shopId.value,
    }

    const { status, data } = await Fetch('shopping/shopInfo/getShopCustomerList', {
      method: 'GET',
      data: params
    })

    if (status === 200 && data.code === 200) {
      const newEmployees = data.data || []

      if (isRefresh) {
        employeeList.value = newEmployees
      } else {
        employeeList.value.push(...newEmployees)
      }

      hasMore.value = newEmployees.length === 10
      page.value++

      // 更新统计信息
      if (data.stats) {
        employeeStats.value = data.stats
      }
    } else {
      uni.showToast({
        title: data?.msg || '获取员工列表失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    loading.value = false
    loadingMore.value = false
    refreshing.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  getEmployeeList(true)
}

const handleClear = () => {
  searchKeyword.value = ''
  getEmployeeList(true)
}

// 筛选切换
const handleFilterChange = (value) => {
  if (activeFilterTab.value === value) return
  activeFilterTab.value = value
  getEmployeeList(true)
}

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true
  await getEmployeeList(true)
}

// 加载更多
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    getEmployeeList()
  }
}

// 查看员工详情
const viewEmployeeDetail = (employee) => {
  uni.navigateTo({
    url: `/pages/EmployeeDetail?id=${employee.id}&shopId=${shopId.value}`
  })
}

// 显示添加员工弹窗
const showAddDialog = () => {
  resetForm()
  isEditing.value = false
  showEmployeeDialog.value = true
}

// 编辑员工
const editEmployee = (employee) => {
  Object.assign(formData, {
    id: employee.id,
    name: employee.name,
    phone: employee.phone,
    jobTitle: employee.jobTitle || '',
    department: employee.department || '',
    joinDate: employee.joinDate,
    status: employee.status,
    avatar: employee.avatar || '',
    remark: employee.remark || ''
  })
  isEditing.value = true
  showEmployeeDialog.value = true
}

// 确认删除
const confirmDelete = (employee) => {
  if (employee.type === 'ADMIN') {
    uni.showToast({
      title: '管理员不能删除',
      icon: 'none'
    })
    return
  }
  console.log(employee, 'employee');
  uni.showModal({
    title: '提示',
    content: `确定要删除 ${employee.customerName} 该员工吗？`,
    confirmText: '删除',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        deleteEmployee(employee.customerId)
      }
    }
  })
}

// 删除员工
const deleteEmployee = async (id) => {
  if (!id) return

  try {
    const { status, data } = await Fetch('shopping/shopInfo/deleteShopCustomer', {
      method: 'delete',
      data: {
        customerId: id ,
        shopId: shopId.value
      }
    })

    if (status === 200 && data.code === 200) {
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      })
      getEmployeeList(true)
    } else {
      uni.showToast({
        title: data?.msg || '删除失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('删除员工失败:', error)
    uni.showToast({
      title: '删除失败',
      icon: 'none'
    })
  } finally {
    currentDeleteEmployee.value = null
    showDeleteConfirm.value = false
  }
}

// 上传头像
const uploadAvatar = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['camera', 'album'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]

      uni.showLoading({
        title: '上传中...'
      })

      try {
        const uploadRes = await uni.uploadFile({
          url: `${baseUrl}shopping/sysFile/upload`,
          filePath: tempFilePath,
          name: 'file',
          header: {
            'accesstoken': loginStore.token
          }
        })

        const result = JSON.parse(uploadRes.data)
        if (result.code === 200) {
          formData.avatar = result.data.fileUrl
          uni.showToast({
            title: '上传成功',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('上传头像失败:', error)
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
  } catch (error) {
    return
  }

  submitting.value = true

  try {
    const apiUrl = isEditing.value ? 'shopping/employee/update' : 'shopping/employee/add'
    const submitData = {
      ...formData,
      shopId: shopId.value
    }

    const { status, data } = await Fetch(apiUrl, {
      method: 'POST',
      data: submitData
    })

    if (status === 200 && data.code === 200) {
      uni.showToast({
        title: isEditing.value ? '保存成功' : '添加成功',
        icon: 'success'
      })
      closeDialog()
      getEmployeeList(true)
    } else {
      uni.showToast({
        title: data?.msg || '操作失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 关闭弹窗
const closeDialog = () => {
  showEmployeeDialog.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    phone: '',
    jobTitle: '',
    department: '',
    joinDate: '',
    status: 1,
    avatar: '',
    remark: ''
  })
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '未设置'
  try {
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  } catch {
    return dateStr
  }
}

// 处理图片加载失败
const handleImageError = (e) => {
  e.target.src = '../static/imgs/touxiang.png'
}

onMounted(() => {
  calcContentHeight()
  uni.onWindowResize && uni.onWindowResize(calcContentHeight)
  getEmployeeList(true)
})
</script>

<style lang="scss" scoped>
.employee-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #F5F5F5;

  .employee-header {
    background: #FFFFFF;
    padding: 20rpx 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #F0F0F0;

    .employee-header-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #191919;
    }

    .employee-header-actions {
      .add-btn {
        display: flex;
        align-items: center;
        padding: 12rpx 20rpx;
        background: #F9DC40;
        border-radius: 20rpx;
        font-size: 28rpx;
        color: #191919;
        font-weight: 500;

        span {
          margin-left: 8rpx;
        }
      }
    }
  }

  .search-section {
    padding: 20rpx 30rpx;
    background: #FFFFFF;
    margin-bottom: 20rpx;
  }

  .stats-section {
    display: flex;
    background: #FFFFFF;
    margin-bottom: 20rpx;

    .stats-item {
      flex: 1;
      text-align: center;
      padding: 30rpx 20rpx;

      .stats-number {
        font-size: 48rpx;
        font-weight: bold;
        color: #F9DC40;
        margin-bottom: 10rpx;
      }

      .stats-label {
        font-size: 26rpx;
        color: #666666;
      }
    }
  }

  .filter-tabs {
    display: flex;
    background: #FFFFFF;
    margin-bottom: 20rpx;

    .filter-tab {
      flex: 1;
      text-align: center;
      padding: 24rpx 20rpx;
      font-size: 28rpx;
      color: #666666;
      border-bottom: 4rpx solid transparent;
      cursor: pointer;

      &.active {
        color: #F9DC40;
        border-bottom-color: #F9DC40;
        font-weight: bold;
      }
    }
  }

  .employee-content {
    flex: 1;
    margin-top: 20rpx;
    padding: 0 30rpx;
    box-sizing: border-box;

    .loading-container,
    .empty-container {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 400rpx;
      color: #999999;

      .loading-text {
        margin-top: 20rpx;
        font-size: 28rpx;
      }

      .empty-text {
        margin: 20rpx 0;
        font-size: 28rpx;
      }

      .empty-btn {
        padding: 20rpx 40rpx;
        background: #F9DC40;
        color: #191919;
        border-radius: 40rpx;
        font-size: 28rpx;
        font-weight: 500;
      }
    }

    .employee-item {
      display: flex;
      align-items: center;
      background: #FFFFFF;
      border-radius: 20rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      position: relative;

      .employee-avatar {
        position: relative;
        margin-right: 30rpx;

        image {
          width: 120rpx;
          height: 120rpx;
          border-radius: 60rpx;
          object-fit: cover;
        }

        .status-badge {
          position: absolute;
          bottom: -5rpx;
          right: -5rpx;
          padding: 4rpx 12rpx;
          border-radius: 20rpx;
          font-size: 20rpx;
          color: #FFFFFF;

          &.status-active {
            background: #52C41A;
          }

          &.status-inactive {
            background: #FF4D4F;
          }
        }
      }

      .employee-info {
        flex: 1;

        .employee-name {
          display: flex;
          align-items: center;
          margin-bottom: 16rpx;

          .name {
            font-size: 32rpx;
            font-weight: bold;
            color: #191919;
            margin-right: 20rpx;
          }

          .job-title {
            font-size: 24rpx;
            color: #666666;
            background: #F5F5F5;
            padding: 4rpx 12rpx;
            border-radius: 12rpx;
          }
        }

        .employee-details {
          .detail-item {
            display: flex;
            align-items: center;
            margin-bottom: 8rpx;
            font-size: 24rpx;
            color: #999999;

            span {
              margin-left: 8rpx;
            }
          }
        }
      }

      .employee-actions {
        display: flex;
        flex-direction: column;

        .action-btn {
          width: 60rpx;
          height: 60rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 30rpx;
          margin-bottom: 16rpx;

          &.edit-btn {
            background: rgba(249, 220, 64, 0.1);
          }

          &.delete-btn {
            background: rgba(255, 107, 107, 0.1);
          }
        }
      }
    }
  }
}

// 弹窗样式
.employee-dialog {
  width: 680rpx;
  max-height: 80vh;
  background: #FFFFFF;
  border-radius: 20rpx;

  .dialog-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 40rpx 40rpx 20rpx;
    border-bottom: 1px solid #F0F0F0;

    .dialog-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #191919;
    }

    .dialog-close {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 30rpx;
      background: #F5F5F5;
    }
  }

  .dialog-content {
    padding: 40rpx;
    max-height: 50vh;
    overflow-y: auto;

    .avatar-upload {
      display: flex;
      justify-content: center;
      margin-bottom: 40rpx;

      .upload-area {
        width: 160rpx;
        height: 160rpx;
        border-radius: 80rpx;
        border: 2rpx dashed #CCCCCC;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background: #FAFAFA;
        position: relative;
        overflow: hidden;

        .uploaded-avatar {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .upload-placeholder {
          text-align: center;
          color: #CCCCCC;
          font-size: 24rpx;

          div {
            margin-top: 10rpx;
          }
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    gap: 20rpx;
    padding: 20rpx 40rpx 40rpx;

    :deep(.wd-button) {
      flex: 1;
    }
  }
}
</style>
